import axios from "axios";
import type { AxiosResponse } from "axios";
import { ElMessage } from "element-plus";
import { isElectron } from "@/utils";
import router from "@/router/index";
// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  baseURL: "/", // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000, // request timeout
});

const urlMap = new Map();
// request interceptor
service.interceptors.request.use(
  (config) => {
    let params;
    const reqUrl: string = [config.url, params, " ", config.method].join("");
    if (config.method === "get") {
      if (config.params) {
        // 防止ie接口缓存
        config.params.__t = new Date().getTime();
      } else {
        config.params = {
          __t: new Date().getTime(),
        };
      }
    }
    if (urlMap.has(reqUrl)) {
      if (reqUrl != "/api/agent/status get") {
        const time = urlMap.get(reqUrl);
        const currentTime = new Date().getTime();
        if (currentTime - time < 300) {
          return Promise.reject("请求重复提交" + reqUrl);
        }
        urlMap.set(reqUrl, currentTime);
      }
      // do something before request is sent
    } else {
      urlMap.set(reqUrl, new Date().getTime());
    }
    return config;
  },
  (error) => {
    // do something with request error
    return Promise.reject(error);
  }
);
// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  async (response: AxiosResponse) => {
    const res = response;
    if (res) {
      const status = Number(res.status)
      if (status === 200) return response.data;

      if (status !== 200) {
        switch (status) {
          case 205:
            if (isElectron()) {
              const { ipcRenderer } = require("electron");
              await ipcRenderer.invoke("isLogout");
            } else {
              router.push("/login");
            }
            break;
          case 400:
            ElMessage({
              message: "错误请求",
              type: "error",
              duration: 5 * 1000,
            });
            break;
          case 401:
            ElMessage({
              message: "未授权，请重新登录",
              type: "error",
              duration: 5 * 1000,
            });
            router.push("/login");
            break;
          case 403:
            ElMessage({
              message: "拒绝访问",
              type: "error",
              duration: 5 * 1000,
            });
            // router.push('/login')
            break;
          case 404:
            ElMessage({
              message: "请求错误,未找到该资源",
              type: "error",
              duration: 5 * 1000,
            });
            break;
          case 405:
            ElMessage({
              message: "请求方法未允许",
              type: "error",
              duration: 5 * 1000,
            });
            break;
          case 408:
            ElMessage({
              message: "请求超时",
              type: "error",
              duration: 5 * 1000,
            });
            break;
          case 500:
            ElMessage({
              message: "服务器端出错",
              type: "error",
              duration: 5 * 1000,
            });
            break;
          case 501:
            ElMessage({
              message: "网络未实现",
              type: "error",
              duration: 5 * 1000,
            });
            break;
          case 502:
            ElMessage({
              message: "网络错误",
              type: "error",
              duration: 5 * 1000,
            });
            break;
          case 503:
            ElMessage({
              message: "服务不可用",
              type: "error",
              duration: 5 * 1000,
            });
            break;
          case 504:
            ElMessage({
              message: "网络超时",
              type: "error",
              duration: 5 * 1000,
            });
            break;
          case 505:
            ElMessage({
              message: "http版本不支持该请求",
              type: "error",
              duration: 5 * 1000,
            });
            break;
        }
      }
      return response.data;
    } else {
      if (!window.navigator.onLine) {
        ElMessage({
          message: "网络中断",
          type: "error",
          duration: 5 * 1000,
        });
        return;
      }
    }
  },
  (error: any) => {
    return Promise.reject(error);
  }
);
export default service;
